<?php
namespace app\admin\controller\sum\gudong;

use addons\sum\service\gudong\Gudong as GudongService;
use think\Db;
use think\exception\HttpResponseException;
use addons\sum\exception\SumException;
use app\admin\model\sum\gudong\Apply as ApplyModel;

/**
 * 申请
 */
class Apply extends \app\admin\controller\sum\Common
{

    public function _initialize()
    {
        \app\admin\controller\sum\Common::_initialize();
        $this->model = new ApplyModel;
    }

    /**
     * 申请列表
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        $records = $this->model->sheepFilter()->with(['user'])->paginate($this->request->param('list_rows', 10));
        $this->success('获取成功', null, $records);
    }

    public function add()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
    }

    public function handle($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $params = $this->request->param();
        $action = $params['action'] ?? null;
        $refuse_msg = $params['refuse_msg'] ?? '';
        if ($action == 'refuse' && !$refuse_msg) {
            $this->error('请输入拒绝原因');
        }

        $ids = is_array($id) ? $id : explode(',', $id);
        foreach ($ids as $key => $id) {
            Db::startTrans();
            try {
                $apply = $this->model->lock(true)->where('id', $id)->find();
                if (!$apply) {
                    $this->error(__('No Results were found'));
                }
                $gudong_service=new GudongService($apply->user_id);
                switch ($action) {
                    case 'agree':
                        $apply = $gudong_service->handleAgree($apply);
                        break;
                    case 'refuse':
                        $apply = $gudong_service->handleRefuse($apply, $refuse_msg);
                        break;
                }

                Db::commit();
            } catch (SumException $e) {
                Db::commit();       // 不回滚，记录错误日志
                $this->error($e->getMessage());
            } catch (HttpResponseException $e) {
                $data = $e->getResponse()->getData();
                $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                $this->error($message);
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->success('处理成功');
    }
}
